//
//  FDCalendarItem.m
//  FDCalendarDemo
//
//  Created by fergusding on 15/8/20.
//  Copyright (c) 2015年 fergusding. All rights reserved.
//

#import "FDCalendarItem.h"
#import <QuartzCore/QuartzCore.h>
#import "CalendarViewController.h"
#import "ReportViewController.h"

@interface FDCalendarCell : UICollectionViewCell

- (UILabel *)dayLabel;
- (UILabel *)chineseDayLabel;
- (UIView *)dayView;

@end

@implementation FDCalendarCell {
    UILabel *_dayLabel;
    UILabel *_chineseDayLabel;
    UIView *_dayView;
}

#pragma mark -
#pragma mark 日期Label
- (UILabel *)dayLabel {
    if (!_dayLabel) {
        _dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
        _dayLabel.textAlignment = NSTextAlignmentCenter;
        _dayLabel.font = [UIFont systemFontOfSize:15];
        _dayLabel.center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2 - 3);
        [self addSubview:_dayLabel];
    }
    return _dayLabel;
}

#pragma mark -
#pragma mark 农历Label
- (UILabel *)chineseDayLabel {
    if (!_chineseDayLabel) {
        _chineseDayLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 10)];
        _chineseDayLabel.textAlignment = NSTextAlignmentCenter;
        _chineseDayLabel.font = [UIFont boldSystemFontOfSize:9];
        CGPoint point = _dayLabel.center;
        point.y += 15;
        _chineseDayLabel.center = point;
        [self addSubview:_chineseDayLabel];
    }
    return _chineseDayLabel;
}
#pragma mark -
#pragma mark 日期View
- (UIView *)dayView
{
    if (!_dayView) {
        _dayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 8)];
        _dayView.backgroundColor = [UIColor greenColor];
        CGPoint point = _dayLabel.center;
        point.y += 15;
        _dayView.center = point;
        [self addSubview:_dayView];
    }
    return _dayView;
}

@end

#define CollectionViewHorizonMargin 5
#define CollectionViewVerticalMargin 5

#define ChineseMonths @[@"正月", @"二月", @"三月", @"四月", @"五月", @"六月", @"七月", @"八月",@"九月", @"十月", @"冬月", @"腊月"]
#define ChineseDays @[@"初一", @"初二", @"初三", @"初四", @"初五", @"初六", @"初七", @"初八", @"初九", @"初十",@"十一", @"十二", @"十三", @"十四", @"十五", @"十六", @"十七", @"十八", @"十九", @"二十", @"廿一", @"廿二", @"廿三", @"廿四", @"廿五", @"廿六", @"廿七", @"廿八", @"廿九", @"三十"]

typedef NS_ENUM(NSUInteger, FDCalendarMonth) {
    FDCalendarMonthPrevious = 0,
    FDCalendarMonthCurrent = 1,
    FDCalendarMonthNext = 2,
};

@interface FDCalendarItem () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (strong, nonatomic) UICollectionView *collectionView;

@end

@implementation FDCalendarItem

- (instancetype)init {
    if (self = [super init]) {
        self.backgroundColor = [UIColor clearColor];
        [self setupCollectionView];
        [self setFrame:CGRectMake(0, 0, DeviceWidth, self.collectionView.frame.size.height + CollectionViewVerticalMargin * 2)];
    }
    return self;
}

#pragma mark - Custom Accessors

- (void)setDate:(NSDate *)date {
    _date = date;
    [self.collectionView reloadData];
}


#pragma mark - Public

#pragma mark -
#pragma mark 获取date的下个月日期
- (NSDate *)nextMonthDate {
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.month = 1;
    NSDate *nextMonthDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:self.date options:NSCalendarMatchStrictly];
    return nextMonthDate;
}

#pragma mark -
#pragma mark 获取date的上个月日期
- (NSDate *)previousMonthDate {
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.month = -1;
    NSDate *previousMonthDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:self.date options:NSCalendarMatchStrictly];
    return previousMonthDate;
}

#pragma mark - Private

#pragma mark -
#pragma mark collectionView显示日期单元，设置其属性
- (void)setupCollectionView {
    CGFloat itemWidth = (DeviceWidth - CollectionViewHorizonMargin * 2) / 7;
    CGFloat itemHeight = itemWidth;
    
    UICollectionViewFlowLayout *flowLayot = [[UICollectionViewFlowLayout alloc] init];
    flowLayot.sectionInset = UIEdgeInsetsZero;
    flowLayot.itemSize = CGSizeMake(itemWidth, itemHeight);
    flowLayot.minimumLineSpacing = 0;
    flowLayot.minimumInteritemSpacing = 0;
    
    CGRect collectionViewFrame = CGRectMake(CollectionViewHorizonMargin, CollectionViewVerticalMargin, DeviceWidth - CollectionViewHorizonMargin * 2, itemHeight * 6);
    self.collectionView = [[UICollectionView alloc] initWithFrame:collectionViewFrame collectionViewLayout:flowLayot];
    [self addSubview:self.collectionView];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView registerClass:[FDCalendarCell class] forCellWithReuseIdentifier:@"CalendarCell"];
}

#pragma mark -
#pragma mark 获取date当前月的第一天是星期几
- (NSInteger)weekdayOfFirstDayInDate {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:1];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self.date];
    [components setDay:1];
    NSDate *firstDate = [calendar dateFromComponents:components];
    NSDateComponents *firstComponents = [calendar components:NSCalendarUnitWeekday fromDate:firstDate];
    return firstComponents.weekday - 1;
}

#pragma mark -
#pragma mark 获取date当前月的总天数
- (NSInteger)totalDaysInMonthOfDate:(NSDate *)date {
    NSRange range = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return range.length;
}

#pragma mark -
#pragma mark 获取某月day的日期
- (NSDate *)dateOfMonth:(FDCalendarMonth)calendarMonth WithDay:(NSInteger)day {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *date;
    
    switch (calendarMonth) {
        case FDCalendarMonthPrevious:
            date = [self previousMonthDate];
            break;
            
        case FDCalendarMonthCurrent:
            date = self.date;
            break;
            
        case FDCalendarMonthNext:
            date = [self nextMonthDate];
            break;
        default:
            break;
    }
    
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];
    [components setDay:day];
    NSDate *dateOfDay = [calendar dateFromComponents:components];
    return dateOfDay;
}

// 获取date当天的农历
//- (NSString *)chineseCalendarOfDate:(NSDate *)date {
//    NSString *day;
//    NSCalendar *chineseCalendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierChinese];
//    NSDateComponents *components = [chineseCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];
//    if (components.day == 1) {
//        day = ChineseMonths[components.month - 1];
//    } else {
//        day = ChineseDays[components.day - 1];
//    }
//
//    return day;
//}

#pragma mark - UICollectionDatasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 42;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"CalendarCell";
    FDCalendarCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    cell.dayLabel.textColor = [UIColor whiteColor];//SXW__设置字体颜色为白色
    cell.chineseDayLabel.textColor = [UIColor grayColor];
    
    //设置原点
    cell.dayView.hidden = YES;
    cell.dayView.layer.cornerRadius = 4;
    cell.dayView.layer.masksToBounds = YES;
    
    NSInteger firstWeekday = [self weekdayOfFirstDayInDate];
    NSInteger totalDaysOfMonth = [self totalDaysInMonthOfDate:self.date];
    NSInteger totalDaysOfLastMonth = [self totalDaysInMonthOfDate:[self previousMonthDate]];
    
    if (indexPath.row < firstWeekday)
    {    // 小于这个月的第一天
        NSInteger day = totalDaysOfLastMonth - firstWeekday + indexPath.row + 1;
        cell.dayLabel.text = [NSString stringWithFormat:@"%ld", (long)day];
        cell.dayLabel.textColor = [UIColor clearColor];//设置颜色
//        cell.dayLabel.hidden = YES;//SXW__隐藏，跟安卓保持一致。
        [cell.dayLabel setBackgroundColor:[UIColor clearColor]];

        //        cell.chineseDayLabel.text = [self chineseCalendarOfDate:[self dateOfMonth:FDCalendarMonthPrevious WithDay:day]];
    }
    else if (indexPath.row >= totalDaysOfMonth + firstWeekday)
    {    // 大于这个月的最后一天
        NSInteger day = indexPath.row - totalDaysOfMonth - firstWeekday + 1;
        cell.dayLabel.text = [NSString stringWithFormat:@"%ld", (long)  day];
        cell.dayLabel.textColor = [UIColor clearColor];//隐藏，用clear
//        cell.dayLabel.hidden = YES;//SXW__隐藏，跟安卓保持一致。
        [cell.dayLabel setBackgroundColor:[UIColor clearColor]];
        //        cell.chineseDayLabel.text = [self chineseCalendarOfDate:[self dateOfMonth:FDCalendarMonthNext WithDay:day]];
    }
    else
    {    // 属于这个月
        cell.dayLabel.hidden = NO;
        NSInteger day = indexPath.row - firstWeekday + 1;
        cell.dayLabel.text= [NSString stringWithFormat:@"%ld", (long)day];
//        if (day == [[NSCalendar currentCalendar] component:NSCalendarUnitDay fromDate:self.date])
//        {//上面判断方法也是iOS8的
            //选中时的背景
//            cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
//            cell.backgroundColor = [UIColor grayColor];//灰色背景
//            cell.layer.cornerRadius = cell.frame.size.height / 2;//切圆
            cell.dayLabel.textColor = TJJMakeColorWithRGB(233, 239, 245);//选中日期的字体颜色为白色
//            cell.chineseDayLabel.textColor = [UIColor grayColor];
//        }
        
        if (TJJiOS8)
        {//如果是iOS8  通过下面代码展示今天对应的日期的切圆灰色背景。
            if (day == [[NSCalendar currentCalendar] component:NSCalendarUnitDay fromDate:self.date])
            {//上面判断方法也是iOS8的
//                    cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
                cell.backgroundColor = [UIColor grayColor];//灰色背景
                cell.layer.cornerRadius = cell.frame.size.height / 2;//切圆
            }
            else
            {
                cell.backgroundColor = [UIColor clearColor];
            }
        }
       
        NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self.date];
        
        for (NSDictionary *b in self.bArray)
        {//日历 绿色圆点的标记
            NSString *object = [b objectForKey:@"uploaddate"];
            int year = [[object substringWithRange:NSMakeRange(0, 4)] intValue];
            int moth = [[object substringWithRange:NSMakeRange(5, 2)] intValue];
            int myDay = [[object substringWithRange:NSMakeRange(8, 2)] intValue];
            if (myDay ==day && components.month == moth &&components.year == year) {
                cell.dayView.hidden = NO;//绿色标记
            }
        }
        // 如果日期和当期日期同年同月不同天, 注：第一个判断中的方法是iOS8的新API, 会比较传入单元以及比传入单元大得单元上数据是否相等，亲测同时传入Year和Month结果错误
//        if (TJJiOS8)
//        {
//
//            // 如果日期和当期日期同年同月不同天, 注：第一个判断中的方法是iOS8的新API, 会比较传入单元以及比传入单元大得单元上数据是否相等，亲测同时传入Year和Month结果错误
//            if ([[NSCalendar currentCalendar] isDate:[NSDate date] equalToDate:self.date toUnitGranularity:NSCalendarUnitMonth] && ![[NSCalendar currentCalendar] isDateInToday:self.date])
//            {
//                
//                // 将当前日期的那天高亮显示
//                if (day == [[NSCalendar currentCalendar] component:NSCalendarUnitDay fromDate:[NSDate date]]) {
//                    NSLog(@"-------- 当天日期%ld",(long)day);
//                    cell.dayLabel.textColor = [UIColor redColor];//                }
//                }
//            }
//        }

//            else if (day > [[NSCalendar currentCalendar] component:NSCalendarUnitDay fromDate:[NSDate date]])
//            {//大于今天的日期设置为白色
//                cell.dayLabel.textColor = TJJMakeColorWithRGB(233, 239, 245);//选中日期的字体颜色为白色
//                cell.chineseDayLabel.textColor = [UIColor grayColor];
//            }
//            else
//            {//这个月小于今天的日期设置为灰色
//                cell.dayLabel.textColor = [UIColor grayColor];
//                cell.chineseDayLabel.textColor = [UIColor grayColor];
//                
//            }
        //        cell.chineseDayLabel.text = [self chineseCalendarOfDate:[self dateOfMonth:FDCalendarMonthCurrent WithDay:day]];
    }
    return cell;
}

#pragma mark -
#pragma mark - 点击查看睡眠报告
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self.date];
    NSInteger firstWeekday = [self weekdayOfFirstDayInDate];//上个月的天数
    NSInteger allDays = [self totalDaysInMonthOfDate:self.date];//这个月的总天数
    NSInteger indexDay = indexPath.row-firstWeekday+1;
    if (indexDay < 1 || indexDay > allDays)
    {//如果是上个月的，或者是下个月的，直接返回，不需要处理
        return ;
    }
    [components setDay:indexPath.row - firstWeekday + 1];//获取点击日历的当天
    //SXW__标记，不用选中
//    NSDate *selectedDate = [[NSCalendar currentCalendar] dateFromComponents:components];
//    if (self.delegate && [self.delegate respondsToSelector:@selector(calendarItem:didSelectedDate:)])
//    {//设置按钮为选中
//        [self.delegate calendarItem:self didSelectedDate:selectedDate];//设置选中日期
//    }
    NSInteger numberOfAdd = 0;//统计判断的个数。如果numberOfAdd最后等于self.bArray的个数，那么就提示没有当天的睡眠报告数据。
    //点击判断
    for (NSDictionary * b in self.bArray)
    {//判断点击的按钮时候有睡眠报告
        numberOfAdd++;
        NSString *reportID = [b objectForKey:@"reportID"];
        NSString *object = [b objectForKey:@"uploaddate"];
        int year = [[object substringWithRange:NSMakeRange(0, 4)] intValue];
        int moth = [[object substringWithRange:NSMakeRange(5, 2)] intValue];
        int myDay = [[object substringWithRange:NSMakeRange(8, 2)] intValue];
        if (myDay ==components.day && components.month == moth &&components.year == year)
        {
            //请求睡眠报告数据  TODO:数据库设计
            
            UILabel * label = [[UILabel alloc] init];
            label.text = @"s";
            
            numberOfAdd = -100;
            UserConfig *config = [UserConfig sharingUserConfig];
            NSDictionary *dic= @{@"Token":[config getToken],@"reportID":reportID};
            AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
            httpManager.requestSerializer = [AFHTTPRequestSerializer serializer];
            httpManager.responseSerializer = [AFHTTPResponseSerializer serializer];
            __weak FDCalendarItem *weakSelf = self;
            //地址
            [httpManager POST:HOME_CALENDAR parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];
                NSDictionary *Dic = [NetworkTool parseJSONStringToNSDictionary:retDic[@"b"]];
                if ([retDic[@"a"] intValue] == 1)
                {
                    //开始时间
                    NSString *startTime = [[NSString alloc] init];
                    //上传日期
                    NSString *uploaddate = [[NSString alloc] init];
                    //结束时间
                    NSString *endtime = [[NSString alloc] init];
                    //睡眠改善
                    NSString *sleepimprovement = [[NSString alloc] init];
                    //控制
                    NSString *Dreammanipulation = [[NSString alloc] init];
                    //报告报告
                    NSString *Sleepreport = [[NSString alloc] init];
                    //报告时长
                    NSString *reporttime = [[NSString alloc] init];
                    //开始时间
                    startTime = [Dic objectForKey:@"starttimfae"];
                    //上传日期
                    uploaddate = [[Dic objectForKey:@"uploaddate"] substringWithRange:NSMakeRange(0, 10)];
                    //结束时间
                    endtime = [Dic objectForKey:@"endtime"];
                    //睡眠改善
                    sleepimprovement = [Dic objectForKey:@"sleepimprovement"];
                    //控制
                    Dreammanipulation = [Dic objectForKey:@"Dreammanipulation"];
                    //报告报告
                    Sleepreport = [Dic objectForKey:@"Sleepreport"];
                    //报告时长
                    reporttime = [Dic objectForKey:@"reporttime"];
                    ReportViewController *report = [[ReportViewController alloc] init];
                    NSMutableData *myReportData = [[NSMutableData alloc] init];//接收符合的数据报告
                    NSMutableString *reportStr = [[NSMutableString alloc] init];//接收原始数据报告
                    //[reportStr appendString:@"0"];
                    for (int i = 0;i < Sleepreport.length; i++)
                    {
                        NSString *b = [Sleepreport substringWithRange:NSMakeRange(i, 1)];
                        if ([b isEqualToString:@"-"])
                        {
                            continue;
                        }
                        else
                        {
                            [reportStr appendString:b];
                        }
                    }
                    NSLog(@"%@",reportStr);
                    //睡眠报告   （睡眠报告数据的个数最大是5）
                    for (int i = 0; i < reportStr.length; i ++)
                    {
                        int eee = [[reportStr substringWithRange:NSMakeRange(i, 1)] intValue];
                        int a = (eee/10)*16+eee%10;
                        Byte byt1[1] = {0};
                        byt1[0] = a;
                        NSData *data = [NSData dataWithBytes:&byt1 length:sizeof(byt1)];
                        [myReportData appendData:data];
                    }
                    if ([sleepimprovement isEqualToString:@"是"]) {
                        report.sleepGaishan = YES;
                    }else{
                        report.sleepGaishan = NO;
                    }
                    
                    if ([Dreammanipulation isEqualToString:@"是"]) {
                        report.dreamKongZhi = YES;
                    }else{
                        report.dreamKongZhi = NO;
                    }
                    //清醒时间
                    report.clearTime = startTime;
                    //传入日期
                    report.currentDate = uploaddate;
                    //用于判断从日历传入
                    report.Calendar = 1;
                    //有没有睡眠报告（日历传入肯定有）
                    report.reportJudge = YES;
                    //睡眠报告DATA
                    report.reprotData = myReportData;
                    [[weakSelf viewController] presentViewController:report animated:YES completion:nil];
                }
                else if ([retDic[@"a"] intValue] == 0)
                {
                    TJJALERT_VIEW((NSString *)retDic[@"b"]);
                }
                else if([retDic[@"a"] intValue] == -1)
                {
                    TJJALERT_VIEW(@"Token 错误");
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                TJJALERT_VIEW(ERROR_NETWORKINFO);
            }];
        }
    }
    if (numberOfAdd == self.bArray.count)
    {
        AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
        delegate.alertAutoOne = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"没有该日期的睡眠记录" delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
        [delegate.alertAutoOne show];
        //0.5S隐藏
        [self performSelector:@selector(closeAlertViewOneFD) withObject:nil afterDelay:0.5];
    }
}
#pragma mark -
#pragma mark 关闭弹窗
- (void)closeAlertViewOneFD
{
    AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
    [delegate.alertAutoOne dismissWithClickedButtonIndex:0 animated:YES];
}

#pragma mark -
#pragma mark 得到此view 所在的viewController
- (UIViewController*)viewController
{
    for (UIView* next = [self superview]; next;next = next.superview)
    {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController
                                          class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}
@end
